/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on May 20, 2012, 1:47:01 PM
 */
package gui;

import dao.ExecRootXML;
import dao.ExecRowXML;
import dao.ExecTableXML;
import dao.ExecXML;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.tree.*;
import org.w3c.dom.Document;
import pojo.Property;
import pojo.Row;
import pojo.Table;

/**
 *
 * @author HoangLiem
 */
public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnTop = new javax.swing.JPanel();
        jToolBar = new javax.swing.JToolBar();
        jbtAddDatabase = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jbtAddTable = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        jbtEditData = new javax.swing.JButton();
        jSplitPane = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeDatabase = new javax.swing.JTree();
        jSplitPaneBody = new javax.swing.JSplitPane();
        jTpTableData = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtaMessage = new javax.swing.JTextArea();
        jPanelDataTable = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtbData = new javax.swing.JTable();
        jtoolBarDataTable = new javax.swing.JToolBar();
        jbtApply = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jbtRefresh = new javax.swing.JButton();
        jTabbedPaneQuery = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtaQuery = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jmiClose = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jmiAddNewDatabase = new javax.swing.JMenuItem();
        jmiAddTable = new javax.swing.JMenuItem();
        jmiAlterTable = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jpnTop.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jToolBar.setRollover(true);

        jbtAddDatabase.setToolTipText("Create database");
        jbtAddDatabase.setFocusable(false);
        jbtAddDatabase.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtAddDatabase.setMaximumSize(new java.awt.Dimension(40, 40));
        jbtAddDatabase.setPreferredSize(new java.awt.Dimension(40, 40));
        jbtAddDatabase.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar.add(jbtAddDatabase);
        jToolBar.add(jSeparator1);

        jbtAddTable.setToolTipText("Add new table to database selected");
        jbtAddTable.setEnabled(false);
        jbtAddTable.setFocusable(false);
        jbtAddTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtAddTable.setMaximumSize(new java.awt.Dimension(40, 40));
        jbtAddTable.setPreferredSize(new java.awt.Dimension(40, 40));
        jbtAddTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar.add(jbtAddTable);
        jToolBar.add(jSeparator3);

        jbtEditData.setToolTipText("Edit data from from table selected");
        jbtEditData.setEnabled(false);
        jbtEditData.setFocusable(false);
        jbtEditData.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtEditData.setMaximumSize(new java.awt.Dimension(40, 40));
        jbtEditData.setPreferredSize(new java.awt.Dimension(40, 40));
        jbtEditData.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar.add(jbtEditData);

        javax.swing.GroupLayout jpnTopLayout = new javax.swing.GroupLayout(jpnTop);
        jpnTop.setLayout(jpnTopLayout);
        jpnTopLayout.setHorizontalGroup(
            jpnTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnTopLayout.createSequentialGroup()
                .addComponent(jToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
                .addContainerGap(299, Short.MAX_VALUE))
        );
        jpnTopLayout.setVerticalGroup(
            jpnTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnTopLayout.createSequentialGroup()
                .addComponent(jToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jSplitPane.setResizeWeight(0.15);
        jSplitPane.setAutoscrolls(true);
        jSplitPane.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jSplitPane.setMinimumSize(new java.awt.Dimension(150, 50));

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTreeDatabase.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTreeDatabase.setAutoscrolls(true);
        jTreeDatabase.setPreferredSize(new java.awt.Dimension(200, 64));
        jTreeDatabase.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTreeDatabaseMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTreeDatabaseMousePressed(evt);
            }
        });
        jTreeDatabase.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeDatabaseValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTreeDatabase);

        jSplitPane.setLeftComponent(jScrollPane1);

        jSplitPaneBody.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jSplitPaneBody.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPaneBody.setResizeWeight(0.6);
        jSplitPaneBody.setAutoscrolls(true);
        jSplitPaneBody.setMinimumSize(new java.awt.Dimension(250, 250));

        jTpTableData.setAutoscrolls(true);
        jTpTableData.setMinimumSize(new java.awt.Dimension(100, 100));
        jTpTableData.setPreferredSize(new java.awt.Dimension(400, 200));

        jtaMessage.setColumns(20);
        jtaMessage.setRows(5);
        jScrollPane3.setViewportView(jtaMessage);

        jTpTableData.addTab("Message", jScrollPane3);

        jtbData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtbData.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jtbData.setRowHeight(10);
        jScrollPane4.setViewportView(jtbData);
        jtbData.getAccessibleContext().setAccessibleParent(jTpTableData);

        jtoolBarDataTable.setRollover(true);

        jbtApply.setToolTipText("Apply data changed");
        jbtApply.setFocusable(false);
        jbtApply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtApply.setMaximumSize(new java.awt.Dimension(30, 30));
        jbtApply.setPreferredSize(new java.awt.Dimension(30, 30));
        jbtApply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtApplyActionPerformed(evt);
            }
        });
        jtoolBarDataTable.add(jbtApply);
        jtoolBarDataTable.add(jSeparator2);

        jbtRefresh.setToolTipText("Refresh all data");
        jbtRefresh.setFocusable(false);
        jbtRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbtRefresh.setMaximumSize(new java.awt.Dimension(30, 30));
        jbtRefresh.setPreferredSize(new java.awt.Dimension(30, 30));
        jbtRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbtRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtRefreshActionPerformed(evt);
            }
        });
        jtoolBarDataTable.add(jbtRefresh);

        javax.swing.GroupLayout jPanelDataTableLayout = new javax.swing.GroupLayout(jPanelDataTable);
        jPanelDataTable.setLayout(jPanelDataTableLayout);
        jPanelDataTableLayout.setHorizontalGroup(
            jPanelDataTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDataTableLayout.createSequentialGroup()
                .addComponent(jtoolBarDataTable, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
        );
        jPanelDataTableLayout.setVerticalGroup(
            jPanelDataTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDataTableLayout.createSequentialGroup()
                .addComponent(jtoolBarDataTable, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
        );

        jTpTableData.addTab("Table Data", jPanelDataTable);

        jSplitPaneBody.setBottomComponent(jTpTableData);
        jTpTableData.getAccessibleContext().setAccessibleName("Message");

        jTabbedPaneQuery.setMinimumSize(new java.awt.Dimension(150, 150));
        jTabbedPaneQuery.setPreferredSize(new java.awt.Dimension(150, 150));

        jtaQuery.setColumns(20);
        jtaQuery.setRows(10);
        jtaQuery.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jtaQuery.setMinimumSize(new java.awt.Dimension(100, 100));
        jScrollPane2.setViewportView(jtaQuery);
        jtaQuery.getAccessibleContext().setAccessibleName("");
        jtaQuery.getAccessibleContext().setAccessibleParent(jSplitPaneBody);

        jTabbedPaneQuery.addTab("", jScrollPane2);

        jSplitPaneBody.setTopComponent(jTabbedPaneQuery);
        jTabbedPaneQuery.getAccessibleContext().setAccessibleName("");

        jSplitPane.setRightComponent(jSplitPaneBody);

        jMenu1.setText("  File ");

        jmiClose.setText("Close");
        jMenu1.add(jmiClose);

        jMenuBar1.add(jMenu1);

        jMenu2.setText(" Edit ");

        jmiAddNewDatabase.setText("Add new database");
        jmiAddNewDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiAddNewDatabaseActionPerformed(evt);
            }
        });
        jMenu2.add(jmiAddNewDatabase);

        jmiAddTable.setText("Add new table");
        jmiAddTable.setToolTipText("Please chose database");
        jmiAddTable.setEnabled(false);
        jmiAddTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiAddTableActionPerformed(evt);
            }
        });
        jMenu2.add(jmiAddTable);

        jmiAlterTable.setText("Alter table");
        jmiAlterTable.setToolTipText("Please chose a table");
        jmiAlterTable.setEnabled(false);
        jMenu2.add(jmiAlterTable);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpnTop, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 672, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = MainFrame.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    void initTree() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        ArrayList<String> databaseNames = ExecRootXML.getDatabaseNamesFromRoot();
        if (!databaseNames.isEmpty()) {
            for (int i = 0; i < databaseNames.size(); i++) {
                //Lay ten database
                String databaseName = databaseNames.get(i);
                DefaultMutableTreeNode databaseNode = new DefaultMutableTreeNode(databaseName);

                //chuan bi lay thong tin table trong databse tuong ung
                Document doc = ExecXML.getDocument(databaseName + ".xml");
                ArrayList<Table> tables = ExecTableXML.getTablesFromDatabase(doc);
                if (tables != null) {
                    for (int t = 0; t < tables.size(); t++) {
                        Table table = tables.get(t);
                        DefaultMutableTreeNode tableNode = new DefaultMutableTreeNode(table.getName());
                        ArrayList<Property> idsTableList = table.getIdList();
                        if (idsTableList != null && !idsTableList.isEmpty()) {
                            for (int id = 0; id < idsTableList.size(); id++) {
                                Property idTable = idsTableList.get(id);
                                DefaultMutableTreeNode idNode = new DefaultMutableTreeNode(idTable.getName());
                                tableNode.add(idNode);
                            }
                        }
                        ArrayList<Property> propertyList = table.getPropertyList();
                        if (propertyList != null && !propertyList.isEmpty()) {
                            for (int p = 0; p < propertyList.size(); p++) {
                                Property propertyTable = propertyList.get(p);
                                DefaultMutableTreeNode propertyNode = new DefaultMutableTreeNode(propertyTable.getName());
                                tableNode.add(propertyNode);
                            }
                        }
                        databaseNode.add(tableNode);
                    }
                }
                root.add(databaseNode);
            }
            DefaultTreeModel model = new DefaultTreeModel(root);
            model.getPathToRoot(root);
            jTreeDatabase.setModel(model);
        }
        jTreeDatabase.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    }
    JPopupMenu rootPopup;
    JPopupMenu databasePopup;
    JPopupMenu tablePopup;

    void createNewDatabase() {
        String name = "";
        do {
            name = JOptionPane.showInputDialog("Please enter database name:");
            name = name.trim();
            if (name.equals("")) {
                showMessage("Database name was not empty");
            }
        } while (name.equals(""));
        if (!name.equals("")) {
            if (ExecRootXML.isExistedDatabase(name)) {
                showMessage("Database name was existed");
            } else {
                name = name.toLowerCase().trim();
                boolean result = ExecRootXML.addNewDatabaseNameToRoot(name);
                if (result) {
                    showMessage("Add database successfully");
                    initTree();
                } else {
                    showMessage("Add database failed");
                }
            }
        }
    }

    void initPopups() {
        //tao menu popup cho node root
        rootPopup = new JPopupMenu();
        JMenuItem rootMenuItem1 = new JMenuItem("    Create database    ");
        JMenuItem rootMenuItem2 = new JMenuItem("    Refresh    ");
        rootPopup.add(rootMenuItem1);
        rootPopup.add(rootMenuItem2);
        rootMenuItem1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                createNewDatabase();
            }
        });
        rootMenuItem2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                initTree();
            }
        });
        //Tao menu popup cho node ten database
        databasePopup = new JPopupMenu();
        JMenuItem databaseMenuItem1 = new JMenuItem("    Create table    ");
        databasePopup.add(databaseMenuItem1);
        databaseMenuItem1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                AddTableDialog addTableDialog = new AddTableDialog(null, true, 1);
                addTableDialog.setSize(800, 400);
                JFrameLocation.centerOnScreen(addTableDialog);
                String[] s = getSelectedNodePath();
                String databaseName = s[s.length - 1].trim();
                addTableDialog.setDatabaseName(databaseName);
                addTableDialog.setTitle("Add new table to \"" + databaseName + "\"");
                addTableDialog.setVisible(true);
            }
        });
        //Tao menu popup cho node ten table
        tablePopup = new JPopupMenu();
        JMenuItem tableMenuItem1 = new JMenuItem("    Alter table    ");
        JMenuItem tableMenuItem2 = new JMenuItem("    Create foreign key    ");
        JMenuItem tableMenuItem3 = new JMenuItem("    Edit data    ");
        tablePopup.add(tableMenuItem1);
        tablePopup.add(tableMenuItem2);
        tablePopup.add(tableMenuItem3);
        tableMenuItem1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                AddTableDialog addTableDialog = new AddTableDialog(null, true, 2);
                addTableDialog.setSize(800, 400);
                JFrameLocation.centerOnScreen(addTableDialog);
                String[] s = getSelectedNodePath();
                String databaseName = s[s.length - 2].trim();
                String tableName = s[s.length - 1].trim();
                addTableDialog.setDatabaseName(databaseName);
                addTableDialog.setTableName(tableName);
                addTableDialog.setTitle("Alter table \"" + tableName + "\" in \"" + databaseName + "\"");
                addTableDialog.setVisible(true);
            }
        });
        tableMenuItem2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                AddForeignKeyDialog fkDialog = new AddForeignKeyDialog(null, true);
                //addTableDialog.setSize(800, 400);
                JFrameLocation.centerOnScreen(fkDialog);
                String[] s = getSelectedNodePath();
                String databaseName = s[s.length - 2].trim();
                String tableName = s[s.length - 1].trim();
                fkDialog.setDatabaseName(databaseName);
                fkDialog.setTableName(tableName);
                fkDialog.setTitle("Create foreign key in \"" + tableName + "\"");
                fkDialog.setVisible(true);
            }
        });
        tableMenuItem3.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String[] s = getSelectedNodePath();
                String databaseName = s[s.length - 2];
                String tableName = s[s.length - 1];
                initToolBarTable();
                initDataTable(databaseName, tableName);
            }
        });
    }

    void init() {
        initTree();
        initPopups();
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        init();
        initToolBar();
        this.jbtApply.setEnabled(false);
        this.jbtRefresh.setEnabled(false);
    }//GEN-LAST:event_formWindowOpened

    private void jTreeDatabaseMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeDatabaseMousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTreeDatabaseMousePressed

    void showMessage(String str) {
        JOptionPane.showMessageDialog(this, str);
    }

    private String[] getSelectedNodePath() {
        String[] s = new String[1];
        try {
            String str = (String) jTreeDatabase.getSelectionPath().toString();
            StringBuilder sb = new StringBuilder(str);
            sb.deleteCharAt(0);
            sb.deleteCharAt(sb.length() - 1);
            s = (sb.toString()).split(",");
        } catch (Exception ex) {
            s[0] = "root";
        }
        return s;
    }

    private void jTreeDatabaseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeDatabaseMouseClicked
        // TODO add your handling code here:
        if (evt.getButton() == MouseEvent.BUTTON3) {
            int selectedNodeDepth = jTreeDatabase.getSelectionPath().getPathCount();
            if (selectedNodeDepth == 1) {
                rootPopup.show(evt.getComponent(), evt.getX() + 20, evt.getY());
            } else if (selectedNodeDepth == 2) {//nut database
                databasePopup.show(evt.getComponent(), evt.getX() + 20, evt.getY());
            } else if (selectedNodeDepth == 3) {//nut table
                tablePopup.show(evt.getComponent(), evt.getX() + 20, evt.getY());
            }
        }
    }//GEN-LAST:event_jTreeDatabaseMouseClicked

    private void jbtApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtApplyActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jbtApplyActionPerformed

    private void jbtRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtRefreshActionPerformed
        // TODO add your handling code here:
        initToolBarTable();
        DataTableModel model = (DataTableModel) jtbData.getModel();
        String databaseName = model.getDatabaseName();
        String tableName = model.getTableName();
        initDataTable(databaseName, tableName);
    }//GEN-LAST:event_jbtRefreshActionPerformed

    private void jmiAddNewDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiAddNewDatabaseActionPerformed
        // TODO add your handling code here:
        createNewDatabase();
    }//GEN-LAST:event_jmiAddNewDatabaseActionPerformed

    private void jmiAddTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiAddTableActionPerformed
        // TODO add your handling code here:
        int selectedNodeDepth = jTreeDatabase.getSelectionPath().getPathCount();
        if (selectedNodeDepth == 2) {
            AddTableDialog addTableDialog = new AddTableDialog(null, true, 1);
            addTableDialog.setSize(800, 400);
            JFrameLocation.centerOnScreen(addTableDialog);
            String[] s = getSelectedNodePath();
            String databaseName = s[s.length - 1].trim();
            addTableDialog.setDatabaseName(databaseName);
            addTableDialog.setTitle("Add new table to \"" + databaseName + "\"");
            addTableDialog.setVisible(true);
        }
    }//GEN-LAST:event_jmiAddTableActionPerformed

    private void jTreeDatabaseValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeDatabaseValueChanged
        // TODO add your handling code here:
        int selectedNodeDepth = jTreeDatabase.getSelectionPath().getPathCount();
        if (selectedNodeDepth == 2) {
            this.jmiAddTable.setEnabled(true);
            this.jmiAlterTable.setEnabled(false);
            this.jbtAddTable.setEnabled(true);
            this.jbtEditData.setEnabled(false);
        } else if (selectedNodeDepth == 3) {
            this.jmiAddTable.setEnabled(false);
            this.jmiAlterTable.setEnabled(true);
            this.jbtAddTable.setEnabled(false);
            this.jbtEditData.setEnabled(true);
        } else {
            this.jmiAddTable.setEnabled(false);
            this.jmiAlterTable.setEnabled(false);
            this.jbtAddTable.setEnabled(false);
            this.jbtEditData.setEnabled(false);
        }
    }//GEN-LAST:event_jTreeDatabaseValueChanged

    //Khu vuc ding nghia table data
    void initToolBarTable() {
        //this.jtoolBarDataTable.setVisible(true);  
        this.jbtApply.setEnabled(true);
        this.jbtRefresh.setEnabled(true);
        Image img1 = new ImageIcon("resources/apply.png").getImage();
        Image resizedImage1 = img1.getScaledInstance(jbtApply.getWidth(), jbtApply.getHeight(), Image.SCALE_DEFAULT);
        jbtApply.setIcon(new ImageIcon(resizedImage1));
        Image img2 = new ImageIcon("resources/refresh.png").getImage();
        Image resizedImage2 = img2.getScaledInstance(jbtRefresh.getWidth(), jbtRefresh.getHeight(), Image.SCALE_DEFAULT);
        jbtRefresh.setIcon(new ImageIcon(resizedImage2));
    }

    void initToolBar() {
        //this.jtoolBarDataTable.setVisible(true);  
         Image img0 = new ImageIcon("resources/adddb.png").getImage();
        Image resizedImage0 = img0.getScaledInstance(jbtAddDatabase.getWidth(), jbtAddDatabase.getHeight(), Image.SCALE_DEFAULT);
        jbtAddDatabase.setIcon(new ImageIcon(resizedImage0));        
        Image img1 = new ImageIcon("resources/addtable.png").getImage();
        Image resizedImage1 = img1.getScaledInstance(jbtAddTable.getWidth(), jbtAddTable.getHeight(), Image.SCALE_DEFAULT);
        jbtAddTable.setIcon(new ImageIcon(resizedImage1));
        Image img2 = new ImageIcon("resources/edit.png").getImage();
        Image resizedImage2 = img2.getScaledInstance(jbtEditData.getWidth(), jbtEditData.getHeight(), Image.SCALE_DEFAULT);
        jbtEditData.setIcon(new ImageIcon(resizedImage2));
 
    }

    void initDataTable(String databaseName, String tableName) {
        this.jTpTableData.setSelectedIndex(1);
        ArrayList<String> columnNames = ExecTableXML.getAllFieldsFromTable(databaseName, tableName);
        ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
        ArrayList<Row> rows = ExecRowXML.getRowsOfTable(databaseName, tableName);

        if (columnNames != null && !columnNames.isEmpty()) {
            if (rows != null && !rows.isEmpty()) {

                for (int i = 0; i < rows.size(); i++) {
                    ArrayList<String> rowData = rows.get(i).getData();
                    ArrayList<Object> obj = new ArrayList<Object>();
                    if (rowData != null && !rowData.isEmpty()) {
                        for (int j = 0; j < rowData.size(); j++) {
                            obj.add(rowData.get(j));
                        }
                        data.add(obj);
                    }
                }
                DataTableModel tempModel = new DataTableModel();
                data.add(tempModel.initNewRow(columnNames.size()));

            }
        }
        DataTableModel model = new DataTableModel(columnNames, data, databaseName, tableName);
        jtbData.setModel(model);
        initColumnSizes(jtbData, columnNames);
    }

    private void initColumnSizes(JTable table, ArrayList<String> columnNames) {
        DataTableModel model = (DataTableModel) table.getModel();
        TableColumn column = null;
        int headerWidth = 120;
        for (int i = 0; i < model.getColumnCount(); i++) {
            column = table.getColumnModel().getColumn(i);
            headerWidth = columnNames.get(i).length() * 10 + 20;
            column.setPreferredWidth(headerWidth);
        }
        jtbData.setRowHeight(18);
    }

    /**
     * @para:)=))m args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanelDataTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSplitPane jSplitPane;
    private javax.swing.JSplitPane jSplitPaneBody;
    private javax.swing.JTabbedPane jTabbedPaneQuery;
    private javax.swing.JToolBar jToolBar;
    private javax.swing.JTabbedPane jTpTableData;
    private javax.swing.JTree jTreeDatabase;
    private javax.swing.JButton jbtAddDatabase;
    private javax.swing.JButton jbtAddTable;
    public javax.swing.JButton jbtApply;
    private javax.swing.JButton jbtEditData;
    public javax.swing.JButton jbtRefresh;
    private javax.swing.JMenuItem jmiAddNewDatabase;
    private javax.swing.JMenuItem jmiAddTable;
    private javax.swing.JMenuItem jmiAlterTable;
    private javax.swing.JMenuItem jmiClose;
    private javax.swing.JPanel jpnTop;
    private javax.swing.JTextArea jtaMessage;
    private javax.swing.JTextArea jtaQuery;
    private javax.swing.JTable jtbData;
    private javax.swing.JToolBar jtoolBarDataTable;
    // End of variables declaration//GEN-END:variables
}
